<template>
  <div class="page-content">
    <div class="header">
      <h3>驾校设置</h3>
    </div>
    <!-- 表格菜单 -->
    <el-tabs v-model="tableLayout" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
      <el-tab-pane label="驾校管理" name="1"> </el-tab-pane>
      <el-tab-pane label="车型分类" name="2"> </el-tab-pane>
      <el-tab-pane label="报名地点" name="3"> </el-tab-pane>
      <el-tab-pane label="招生员" name="4"> </el-tab-pane>
      <el-tab-pane label="教练管理" name="5"> </el-tab-pane>
      <el-tab-pane label="训练场" name="6"> </el-tab-pane>
    </el-tabs>
    <!-- 表格菜单 -->

    <el-form label-width="95px" style="margin-top: 20px">
      <el-form-item label="驾校ID：">
        <el-input v-model="sys.storeId" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <el-form-item label="驾校名称：">
        <el-input v-model="sys.name" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <el-form-item label="联系人：">
        <el-input v-model="sys.contactPerson" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <el-form-item label="联系电话：">
        <el-input v-model="sys.phone" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <el-form-item label="营业时间：">
        <el-input v-model="sys.serveTime" :disabled="!isEdit" placeholder="周一到周五 9:00-18:00" style="width: 500px" />
      </el-form-item>
      <el-form-item label="驾校地址：">
        <el-input v-model="sys.address" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <el-form-item label="地图定位：">
        <el-row :gutter="12">
          <el-col :span="6"><el-button :disabled="!isEdit" @click="showMapDialog = true">选择经纬度</el-button></el-col>
          <el-col :span="6"><el-input v-model="sys.latitude"></el-input></el-col>
          <el-col :span="6"><el-input v-model="sys.longitude"></el-input></el-col>
        </el-row>
      </el-form-item>
      <!-- 主图部分 -->
      <el-form-item label="驾校LOGO：">
        <el-input v-model="sys.mainImage" style="display: none"></el-input>
        <div class="avatar-uploader" @click="openImageDialog(true)">
          <el-image v-if="sys.mainImage" :src="sys.mainImage" class="avatar" fit="contain"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="sys.mainImage" class="mask">替换</div>
          <el-icon v-if="sys.mainImage" class="del-image" :size="20" @click.stop="handleDelImg('logo')">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>
      <!-- end主图部分 -->
      <!-- 轮播图部分 -->
      <!-- <el-form-item label="轮播图：">
        <div :class="imageUrls.length ? '' : 'avatar-uploader'" @click="openImageDialog(false)"
          style="min-height: 150px; display: flex; flex-wrap: wrap;">
          <template v-if="imageUrls.length">
            <div v-for="(url, idx) in imageUrls" :key="url + idx" class="avatar-item">
              <el-image :src="url" class="avatar" fit="contain" />
              <div class="mask">替换</div>
              <el-icon class="del-image" :size="20" @click.stop="handleDelImg(idx)">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </template>
<template v-else>
            <i class="el-icon-plus avatar-uploader-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </i>
          </template>
</div>
</el-form-item> -->
      <el-form-item label="轮播图：">
        <div :class="imageUrls.length ? '' : 'avatar-uploader'" @click="openImageDialog(false)"
          style="min-height: 150px; display: flex; flex-wrap: wrap">
          <template v-if="imageUrls.length">
            <div v-for="(url, idx) in imageUrls" :key="url + idx" class="avatar-item">
              <el-image :src="url" class="avatar" fit="contain" />
              <div class="mask" @click.stop="openImageDialog(false, idx)">替换</div>
              <el-icon class="del-image" :size="20" @click.stop="handleDelImg(idx)">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </template>
          <template v-else>
            <i class="el-icon-plus avatar-uploader-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </i>
          </template>
        </div>
      </el-form-item>
      <!-- end轮播图部分 -->
      <!-- 宣传视频部分 -->
      <el-form-item label="宣传视频：">
        <el-input v-model="sys.promoVideo" style="display: none"></el-input>
        <div class="avatar-uploader" @click="showVideoChooseDialog = true">
          <video v-if="promoVideo" :src="promoVideo" class="avatar" fit="contain"></video>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="promoVideo" class="mask">替换</div>
          <el-icon v-if="promoVideo" class="del-image" :size="20" @click.stop="handleDelImg('video')">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>
      <el-form-item label="成立时间：">
        <el-input v-model="sys.foundTime" :disabled="!isEdit" style="width: 500px" />
      </el-form-item>
      <!-- end宣传视频部分 -->
      <el-form-item label="驾校面积：">
        <el-input v-model="sys.area" :disabled="!isEdit" style="width: 500px">
          <template #append> ㎡ </template>
        </el-input>
      </el-form-item>
      <el-form-item label="教练数：">
        <el-input v-model="sys.coachCount" :disabled="!isEdit" style="width: 500px">
          <template #append> 人 </template>
        </el-input>
      </el-form-item>
      <el-form-item label="车辆数量：">
        <el-input v-model="sys.carCount" :disabled="!isEdit" style="width: 500px">
          <template #append> 辆 </template>
        </el-input>
      </el-form-item>
      <el-form-item label="配套设施：">
        <el-checkbox-group v-model="facilities">
          <el-checkbox v-for="item in additionalServicesList" :key="item.value" :label="item.label" :value="item.value"
            :disabled="!isEdit" size="large" />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="附加服务：">
        <el-checkbox-group v-model="serveElse">
          <el-checkbox v-for="item in additionalServices" :key="item.value" :value="item.value" :disabled="!isEdit"
            :label="item.label" size="large" />
        </el-checkbox-group>
      </el-form-item>
      <!-- 驾校简介 -->
      <el-form-item label="驾校简介：" style="width: 70%">
        <ArtWangEditor v-model="sys.description" />
      </el-form-item>
      <!-- end驾校简介 -->
      <el-form-item>
        <el-button type="primary" style="width: 90px" v-if="!isEdit" @click="edit">
          编辑
        </el-button>
        <el-button type="primary" style="width: 90px" v-if="isEdit" @click="handleSave" :loading="btnLoding">
          保存
        </el-button>
      </el-form-item>
    </el-form>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
      :operationType="false"></image-selected-dialog>
    <video-group-dialog v-if="showVideoChooseDialog" :show-video-choose-dialog="showVideoChooseDialog"
      :single-type="singleType" :operation-type="false" @close-dialog="handleCloseVideoDialog" />

    <map-dialog v-if="showMapDialog" :show-map-dialog-visible="showMapDialog" @cancel="showMapDialog = false"
      @location-selected="selectMapAddress"></map-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getDriverSchoolInfo,
  EditDriverSchoolInfo,
  AddDriverSchoolInfo
} from '@/api/driverSchoolApi'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import VideoGroupDialog from '@/views/decoration/diyComponents/VideoGroupDialog.vue'
import MapDialog from './components/MapSelectorDialog.vue'

const tableLayout = ref('1')
const btnLoding = ref(false)

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const singleType = ref(true)
const showVideoChooseDialog = ref(false)
const showMapDialog = ref(false)

//配套措施
const additionalServicesList = [
  {
    label: '食堂',
    value: '1'
  },
  {
    label: '免费WIFI',
    value: '2'
  },
  {
    label: '商店',
    value: '3'
  },
  {
    label: '储物箱',
    value: '4'
  },
  {
    label: '网吧',
    value: '5'
  },
  {
    label: '咖啡厅',
    value: '6'
  },
  {
    label: '浴室',
    value: '7'
  },
  {
    label: '休息区',
    value: '8'
  }
]

const additionalServices = [
  {
    label: '分期付款',
    value: '1'
  },
  {
    label: '上门收费',
    value: '2'
  },
  {
    label: '科三/科四同天考',
    value: '3'
  },
  {
    label: '专车接送',
    value: '4'
  }
]

const router = useRouter() // 使用useRouter获取路由实例

const driverId = parseInt(localStorage.getItem('lty-store-id') || '0')
const userId = parseInt(localStorage.getItem('userid') || '0')
console.log(userId, 'userId=')

// 驾校id
const facilities = ref(['1'])
const serveElse = ref(['1'])

// 驾校id
const sys: any = ref({
  storeId: driverId,
  name: '',
  contactPerson: '',
  phone: '',
  address: '',
  mainImage: '',
  carouselImages: '',
  promoVideo: '  ',
  area: '',
  coachCount: ' ',
  facilities: [],
  description: '',
  serveTime: '',
  carCount: '',
  serveElse: [],
  foundTime: '',
  latitude: '',
  longitude: ''
})
const isEdit = ref(false)
const imageUrls = ref<string[]>([])
async function handleSave() {
  isEdit.value = !isEdit.value
  try {
    btnLoding.value = true
    let params = {
      storeId: sys.value.storeId,
      name: sys.value.name,
      contactPerson: sys.value.contactPerson,
      phone: sys.value.phone,
      address: sys.value.address,
      mainImage: sys.value.mainImage,
      carouselImages: imageUrls.value.join(','),
      area: sys.value.area,
      coachCount: sys.value.coachCount,
      facilities: facilities.value.join(','),
      description: sys.value.description,
      serveTime: sys.value.serveTime,
      carCount: sys.value.carCount,
      serveElse: serveElse.value.join(','),
      foundTime: sys.value.foundTime,
      promoVideo: promoVideo.value,
      latitude: sys.value.latitude,
      longitude: sys.value.longitude
    }
    if (sys.value.id) {
      let res = await EditDriverSchoolInfo({ id: sys.value.id, ...params })
      if (res.code === '00000') {
        getDriverData()
      }
    } else {
      let res = await AddDriverSchoolInfo(params)
      if (res.code === '00000') {
        getDriverData()
      }
    }
  } catch (error) {
  } finally {
    btnLoding.value = false
  }
}

const edit = () => {
  isEdit.value = !isEdit.value
}
console.log(sys.value, 'sys.value=====12312')

const mainImage = ref('')
const carouselImages = ref<UploadFile[]>([])
const promoVideo = ref('')

const getDriverData = async () => {
  const res = await getDriverSchoolInfo(driverId)
  if (res.code === '00000' && res.data) {
    sys.value = res.data
    facilities.value = sys.value.facilities ? sys.value.facilities.split(',') : ''
    serveElse.value = sys.value.serveElse ? sys.value.serveElse.split(',') : ''
    mainImage.value = sys.value.mainImage ? sys.value.mainImage : ''
    imageUrls.value = sys.value.carouselImages ? sys.value.carouselImages.split(',') : []
    carouselImages.value = Array.isArray(imageUrls.value)
      ? imageUrls.value.map((url, idx) => ({
        name: url.split('/').pop() || `image_${idx + 1}`,
        url,
        status: 'success',
        uid: Date.now() + idx
      }))
      : []
    promoVideo.value = sys.value.promoVideo ? sys.value.promoVideo : ''
  }
  console.log(sys.value, 'sys.value')
}

const handleClick = (e: any) => {
  console.log(e, 'e===')
  if (e === '1') {
    setTimeout(() => {
      router.push('/drivingschool/DrivingschoolManagement')
    }, 0)
  } else if (e === '2') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type')
    }, 0)
  } else if (e === '3') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_baoming')
    }, 0)
  } else if (e === '4') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_zhaosheng')
    }, 0)
  } else if (e === '5') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_jiaolian')
    }, 0)
  } else if (e === '6') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_xunlianchang')
    }, 0)
  }
}

const replaceImageIndex = ref(-1)
const openImageDialog = (isSingle: boolean, idx: number = -1) => {
  selectImageSingle.value = isSingle
  showImageChooseDialog.value = true
  replaceImageIndex.value = idx // -1 表示新增，>=0 表示替换
}

const handleCloseImageDialog = (value: any) => {
  // 没有选中图片，直接关闭弹窗
  if (!value || (Array.isArray(value) && value.length === 0)) {
    showImageChooseDialog.value = false
    replaceImageIndex.value = -1
    return
  }
  if (selectImageSingle.value) {
    sys.value.mainImage = value.fileUrl
  } else {
    if (replaceImageIndex.value >= 0 && value && value.length) {
      // 替换某一张
      imageUrls.value.splice(replaceImageIndex.value, 1, value[0].fileUrl)
    } else if (value && value.length) {
      // 新增/整体替换
      imageUrls.value = value.map((img: any) => img.fileUrl)
    }
    sys.value.carouselImages = imageUrls.value.join(',')
  }
  showImageChooseDialog.value = false
  replaceImageIndex.value = -1 // 重置
}
const handleDelImg = (index: any) => {
  if (index === 'logo') {
    sys.value.mainImage = ''
  } else if (index === 'video') {
    promoVideo.value = ''
  } else {
    imageUrls.value.splice(index, 1)
  }
}

const handleCloseVideoDialog = (value: any) => {
  if (value && value.fileUrl) {
    promoVideo.value = value.fileUrl
  }
  showVideoChooseDialog.value = false
}

function selectMapAddress(value: any) {
  sys.value.latitude = value.lat
  sys.value.longitude = value.lng
  showMapDialog.value = false
}

onMounted(() => {
  getDriverData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  min-width: 150px;
  min-height: 150px;
  line-height: 150px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-item {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 150px;
  height: 150px;
  margin-right: 8px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  position: relative;
  overflow: hidden;

  // 默认隐藏mask
  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
    cursor: pointer;
  }

  // 悬停时显示mask
  &:hover .mask {
    opacity: 1;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.editor-wrapper {
  z-index: 0 !important;
}
</style>
